package cn.restcloud.example.controller.mongo;

import java.util.ArrayList;
import java.util.List;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import cn.restcloud.framework.core.annotation.bean.BeanConfig;
import cn.restcloud.framework.core.annotation.bean.BeanType;
import cn.restcloud.framework.core.annotation.rest.MethodType;
import cn.restcloud.framework.core.annotation.rest.RestConfig;
import cn.restcloud.framework.core.util.db.mongo.MongoUtil;
import cn.restcloud.framework.view.base.DocAndView;
import cn.restcloud.framework.view.util.ViewUtil;

/**
 * 链接mongodb并进行数据报表的示例代码
 * @author Thinkpad
 *
 */

@BeanConfig(appId = "example",beanId = "MongoReportApiRest",beanName = "Mongo数据库统计查询",beanType = BeanType.CONTROLLER,autowired = true,singleton = true,hotMode = true)
@RestConfig(url = "/rest/example/mongo/report")
public class MongoReportApiRest {

	@RestConfig(configName = "按日期统计调用次数",method = MethodType.GET,url = "/bydate")
	public DocAndView report() throws Exception{
		String dbName="RC_APILOG_2020-03-12";
		String collectionName="P_ActionUrlAccessLog";
		String startDayStr="2020-03-10";
        MongoCollection<Document> mc=MongoUtil.getLogMongoClient().getDatabase(dbName).getCollection(collectionName);
        List<Bson> filters=new ArrayList<Bson>();
        filters.add(BsonDocument.parse("{'$match':{'accessDate':{$gt:'"+startDayStr+"'}}}"));
        filters.add(BsonDocument.parse("{$group : {_id : '$accessDate', total : {$sum : 1}}}"));
        filters.add(BsonDocument.parse("{'$sort':{total:-1}}"));
        filters.add(BsonDocument.parse("{ $limit : 100 }"));
        
        AggregateIterable<Document> aggdocs=mc.aggregate(filters);
        List<Document> docs=new ArrayList<Document>();
        for(Document doc:aggdocs) {
        	Document newdoc=new Document();
        	newdoc.putAll((Document)doc.get("_id")); //把id中的字段放入到新的newdoc中
        	newdoc.put("total", doc.get("total")); //取统计结果
        	docs.add(newdoc);
        }
        return ViewUtil.getJsonView(docs);
	}
	

	
}
